﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.IO;

namespace YH.Bluetooth
{
    public class FlexoDllUtil
    {
        // 确定应用程序的基础目录
        private static readonly string _appPath = Path.GetDirectoryName(typeof(FlexoDllUtil).Assembly.Location);
        // 加载所需的 DLL 文件
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr LoadLibrary(string lpFileName);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern bool FreeLibrary(IntPtr hModule);
        public FlexoDllUtil()
        {
            // 使用一个列表来保存已加载的库句柄，以便稍后可以释放它们
            var loadedLibraries = new List<IntPtr>();

            try
            {
                foreach (var dll in new[] { "libssp-0.dll", "libquadmath-0.dll", "libstdc++-6.dll", "FlexoDllUtil.dll" })
                {
                    string fullPath = Path.Combine(_appPath, dll);
                    IntPtr handle = LoadLibrary(fullPath);
                    if (handle == IntPtr.Zero)
                    {
                        throw new Exception($"Failed to load library: {fullPath}, Error: {Marshal.GetLastWin32Error()}");
                    }
                    loadedLibraries.Add(handle);
                }
            }
            catch (Exception ex)
            {
                // 如果加载失败，尝试释放已经加载的库
                foreach (var handle in loadedLibraries)
                {
                    FreeLibrary(handle);
                }
                throw ex; // 重新抛出异常
            }
        }
        /// <summary>
        /// 初始化
        /// </summary>
        [DllImport("FlexoDllUtil.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void init();

        /// <summary>
        /// 停止计算，清空缓存池
        /// </summary>
        [DllImport("FlexoDllUtil.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void stop();

        /// <summary>
        /// 获取eeg报告
        /// </summary>
        [DllImport("FlexoDllUtil.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern string getEeg(
            [In] float[] eegArr,
            int eegLet,
            [In] float[] accXArr,
            [In] float[] accYArr,
            [In] float[] accZArr,
            int imuLet,
            int s);

    }
}
